package com.mswordutil.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

public abstract class ImgHelper {

	public InputStream setImgByUrl(String url){
        GetMethod method = new GetMethod(url);
        HttpClient client = new HttpClient();
        InputStream is = null;
        try {
            int statusCode = client.executeMethod(method);
            if(statusCode!=HttpStatus.SC_OK){
            	System.out.println("无法抓取到图片，抓取地址为：" + url + ",状态码为："+statusCode);
            }else{
            	is = method.getResponseBodyAsStream();
            	setIntoWord(is);
            }
        } catch (Exception e) {
        	e.printStackTrace();
        	System.out.println("无法抓取到图片，抓取地址为：" + url);
        } finally{
        	if(is!=null){
        		try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        	method.releaseConnection();
        }
        return null;
    }
	
	public int[] getImgWidthHeight(InputStream is){
		int[] ia = new int[2];
        try {     

        	BufferedImage bi = ImageIO.read(is);
        	ia[0] = bi.getWidth();
        	ia[1] = bi.getHeight();
        	
        }catch(Exception e){
        	
        }finally{
        	if(is!=null){
        		try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
        	}
        }
        return ia;
	}
	
	public ByteArrayOutputStream inputStream2ByteArrayOutputStream(InputStream is) throws IOException{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
    	byte[] buffer = new byte[1024];
    	int len;
    	while ((len = is.read(buffer)) > -1 ) {
    		baos.write(buffer, 0, len);
    	}
    	baos.flush();	
        return baos;
	}
	
	public abstract void setIntoWord(InputStream is);
}
